package com.jinghua.treatment.wechat.util;

import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.wechat.entity.WXJSConfig;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * 微信的一些全局变量存储和方法
 */

public class WechatUtil {

    static Logger logger = LogManager.getLogger(WechatUtil.class);

    final static long ACCESS_TOKEN_EXPIRED = 7000*1000;//微信token 过期时间 为7200秒，这里保留阈值时间
    /**
     * 访问票根，7200秒需要重新获取一次
     */
    public static String accessToken;
    private static Date storeTimeOfAccess;

    /**
     * 获取微信API的accessToken
     *
     * @return
     */
    public static String getAccessToken() {
        if(accessToken != null){//有值都话看看是否过期
            if(new Date().getTime() - storeTimeOfAccess.getTime()<ACCESS_TOKEN_EXPIRED){
                return  accessToken;
            }
        }
        String result = HttpUtil.sendGetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + PropertyUtil.getConfig("wechat.appId") + "&secret=" + PropertyUtil.getConfig("wechat.secret"), null);
        logger.debug("get access_token result:" + result);

        JSONObject jsonObject = JSONObject.parseObject(result);

        if (jsonObject.getString("access_token") != null) {
            accessToken = (String) jsonObject.get("access_token");
            storeTimeOfAccess = new Date();
            logger.debug("get access_token success:" + accessToken);
        } else {
            //TODO 需要设计全局异常处理代码
            logger.debug("get access_token erroe:" + accessToken);
           // throw new BizErrorException("获取微信access_token失败");
        }
        return   accessToken;
    }
    //
   /* public static void parseJsonToObject(String json ,Object targetObj){

    }*/
    /**
     * 签名算法
     */
    public static String wxSign(WXJSConfig wxjsConfig,String url){
        String nonceStr = wxjsConfig.getNonceStr();
        String jsapi_ticket = wxjsConfig.getJsapi_ticket();
        String seed ="jsapi_ticket="+jsapi_ticket+"&noncestr="+nonceStr+"&timestamp="+wxjsConfig.getTimestamp()+"&url="+url;
        String sha1 = getSha1(seed);
        return  getSha1(seed);
    }

    public static String getSha1(String str){
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    

}
